package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;
/*

    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }
*/

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean b = bookService.save(book);
        System.out.println(b);
        return new Result(b ? Code.SAVE_OK : Code.SAVE_ERR,
                b ? "添加成功" : "添加失败",
                b);
    }



/*

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }
*/

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = bookService.delete(id);
        System.out.println(b);
        return new Result(b ? Code.DELETE_OK : Code.DELETE_ERR,
                b ? "删除成功" : "删除失败",
                b);

    }

/*

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

*/

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean b = bookService.update(book);
        System.out.println(b);
        return new Result(b ? Code.UPDATE_OK : Code.UPDATE_ERR,
                b ? "修改成功" : "修改失败",
                b);

    }
    /*
    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
*/

    @GetMapping
    public Result getAll() {
        List<Book> list = bookService.getAll();
        System.out.println(list);
        return new Result(Code.GET_OK,
                "查询成功",
                list);
    }

/*

    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }
*/


    @GetMapping("/{id}")
    public Result getById(@RequestBody Integer id) {
        Book book = bookService.getById(id);
        System.out.println(book);
        return new Result(book != null ? Code.GET_OK : Code.GET_ERR,
                book != null ? "查询成功" : "查无信息",
                book);
    }



}
